package com.woniuxy.microgoldservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.microgoldservice.bean.*;
import com.woniuxy.microgoldservice.mapper.GoldAccumulateMapper;
import com.woniuxy.microgoldservice.mapper.GoldPriceMapper;
import com.woniuxy.microgoldservice.service.IGoldAccumulateService;
import com.woniuxy.microgoldservice.utils.CodeEnum;
import com.woniuxy.microgoldservice.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author hongbin
 * @date 2021-04-07 14:21
 * Description：黄金产品
 */
@Service
public class GoldAccumulateServiceImpl implements IGoldAccumulateService {
    @Resource
    private GoldAccumulateMapper goldAccumulateDao;

    @Resource
    private GoldPriceMapper goldPriceMapper;


    /**
     * @Author: hongbin
     * @Description: 查询所有黄金商品
     * @DateTime: 9:20 2021/4/16
     * @Params: [name]
     * @Return java.util.List<com.woniuxy.microgoldservice.bean.GoldAccumulateInfo>
     */
    @Override
    public List<GoldAccumulateInfo> selectAll(String name) {
        if (name == null || name.isEmpty()) {
            return goldAccumulateDao.selectAll(null);
        }

        String pattern = "^[\\u4e00-\\u9fa5]*$";
        boolean isMatch = Pattern.matches(pattern, name);
        if (isMatch) {
            String newName = "%" + name + "%";
            return goldAccumulateDao.selectAll(newName);
        }

        ArrayList<GoldAccumulateInfo> objects = new ArrayList<>();
        objects.add(new GoldAccumulateInfo());
        return objects;
    }


    /**
     * @Author: hongbin
     * @Description: 插入产品信息
     * @DateTime: 9:20 2021/4/16
     * @Params: [goldAccumulateInfo]
     * @Return int
     */
    @Override
    public int insert(GoldAccumulateInfo goldAccumulateInfo) {
        return goldAccumulateDao.insert(goldAccumulateInfo);
    }

    /**
     * @Author: hongbin
     * @Description: 更新产品信息
     * @DateTime: 9:21 2021/4/16
     * @Params: [goldAccumulateInfo]
     * @Return int
     */
    @Override
    public int update(GoldAccumulateInfo goldAccumulateInfo) {
        return goldAccumulateDao.update(goldAccumulateInfo);
    }

    /**
     * @Author: hongbin
     * @Description: 批量删除商品
     * @DateTime: 9:21 2021/4/16
     * @Params: [ids]
     * @Return int
     */
    @Override
    public int delete(Long[] ids) {
        return goldAccumulateDao.delete(ids);
    }

    /**
     * @author: hongbin
     * Date: 2021/4/16:9:22
     * Description:查询产品信息
     */
    @Override
    public Long selectIdByType(String type) {
        return goldAccumulateDao.selectIdByType(type);
    }

    /**
     * @Author: hongbin
     * @Description: 查询所有的金价数据源
     * @DateTime: 9:23 2021/4/16
     * @Params: []
     * @Return java.util.List<com.woniuxy.microgoldservice.bean.GoldDataTypeInfo>
     */
    @Override
    public List<GoldDataTypeInfo> getAllTypeName() {
        return goldAccumulateDao.getAllTypeName();
    }

    /**
     * @Author: hongbin
     * @Description: 产品上架，下架
     * @DateTime: 9:23 2021/4/16
     * @Params: [id, accountState]
     * @Return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int goodsShelves(int id, int accountState) {
        int i = goldAccumulateDao.soldOut(id);
        return goldAccumulateDao.goodsShelves(id, accountState);
    }

    /**
     * @Author: hongbin
     * @Description: 查询风险等级
     * @DateTime: 9:24 2021/4/16
     * @Params: []
     * @Return java.util.List<com.woniuxy.microgoldservice.bean.RiskGrade>
     */
    @Override
    public List<RiskGrade> getRiskGrade() {
        return goldAccumulateDao.getRiskGrade();
    }

    /**
     * @Author: hongbin
     * @Description: 查询金价数据源
     * @DateTime: 9:25 2021/4/16
     * @Params: []
     * @Return java.util.List<com.woniuxy.microgoldservice.bean.GoldPAITpye>
     */
    @Override
    public List<GoldPAITpye> getGoldAPITpyes() {
        return goldAccumulateDao.getGoldAPITpyes();
    }

    /**
     * @Author: hongbin
     * @Description: 查询商品通过id
     * @DateTime: 9:25 2021/4/16
     * @Params: [id]
     * @Return com.woniuxy.microgoldservice.bean.GoldAccumulateInfo
     */
    @Override
    public GoldAccumulateInfo selectOne(Long id) {
        return goldAccumulateDao.selectById(id);
    }

    /**
     * @Author: hongbin
     * @Description: 查询回收站中的商品
     * @DateTime: 9:26 2021/4/16
     * @Params: [name]
     * @Return java.util.List<com.woniuxy.microgoldservice.bean.GoldAccumulateInfo>
     */
    @Override
    public List<GoldAccumulateInfo> selectDeleteData(String name) {
        if (!name.equals("") && name.isEmpty()) {
            return goldAccumulateDao.selectDeleteData(null);
        }

        String pattern = "^[\\u4e00-\\u9fa5]*$";
        boolean isMatch = Pattern.matches(pattern, name);
        if (isMatch) {
            String newName = "%" + name + "%";
            return goldAccumulateDao.selectDeleteData(newName);
        }
        ArrayList<GoldAccumulateInfo> objects = new ArrayList<>();
        objects.add(new GoldAccumulateInfo());
        return objects;
    }

    /**
     * @Author: hongbin
     * @Description: 恢复一条商品信息
     * @DateTime: 9:26 2021/4/16
     * @Params: [id]
     * @Return int
     */
    @Override
    public int recoverData(Long id) {
        return goldAccumulateDao.recoverData(id);
    }

    /**
     * @Author: hongbin
     * @Description: 批量删除商品
     * @DateTime: 9:26 2021/4/16
     * @Params: [ids]
     * @Return int
     */
    @Override
    public int completelyDelete(Long[] ids) {
        return goldAccumulateDao.completelyDelete(ids);
    }

    /**
     * @Author: hongbin
     * @Description: app页面展示的商品信息
     * @DateTime: 9:27 2021/4/16
     * @Params: []
     * @Return java.lang.String
     */
    @Override
    public ResultBean selectProduct() {
        GoldAccumulateInfo pro = goldAccumulateDao.selectProduct();
        GoldPriceDTO dto = new GoldPriceDTO();
        dto.setId("黄金信息id");


        GoldPriceInfo priceInfo = null;
        try {
            priceInfo = goldPriceMapper.selectNowPrice(pro.getId());
            //支持付款的银行
            List<BankInfo> bankInfos = goldPriceMapper.selectBank();

            //top
            HashMap<String, Double> map = getTopParam(pro, priceInfo);
            dto.setBoxTop(map);

            //safetyGuarantee 安全保障
//            ArrayList<Object> list = getSaftyGuarantee();
//            dto.setSafetyGuarantee(list);

            //安全保障协议
            dto.setSafetyGuaranteeText("这是什么");

            //transactionRules 交易规则
            HashMap<String, Object> map5 = new HashMap<>();

            //购买服务
            HashMap<String, Object> map6 = getPurchaseReceive(pro);
            map5.put("purchaseReceive", map6);

            String[] split = pro.getCostRule().split("；");


            //earningsCost 收益花费
            HashMap<String, Object> earningsCost = getEarningsCost("interestBearingRules", pro.getInterestRule(), "costRule", split);
            map5.put("earningsCost", earningsCost);

            //支持的银行
            List supportBankList = getSupportBank(bankInfos);
            map5.put("supportBankList", supportBankList);

            dto.setTransactionRules(map5);


            //信息披露 产品信息
            HashMap<String, Object> informationDisclosure = new HashMap<>();

            HashMap<String, Object> basicInformation = getProductInfo(pro);
            informationDisclosure.put("basicInformation", basicInformation);

            //查看协议
//            ArrayList<Map<String, Object>> lookProtocol = getProtocol();
//            informationDisclosure.put("lookProtocol", lookProtocol);

            dto.setInformationDisclosure(informationDisclosure);


            /*Date date = new Date();
            String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
            String year = new SimpleDateFormat("yyyy").format(date);
            List<String> wordDay = DateUtils.judgeWorkDay(year.compareTo(year));
            boolean contains = wordDay.contains(format);*/
            //判断是否可以交易

            Integer startTime = pro.getStartTime();
            Integer startHour = pro.getStartHour();
            Integer endTime = pro.getEndTime();
            Integer endHour = pro.getEndHour();

            if(DateUtils.judgeDealDay(startTime, startHour, endTime, endHour)){
                dto.setStatus(1);
            }else{
                dto.setStatus(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.builder().code(Integer.parseInt(CodeEnum.GOLD_HISTORY_INFO.getCode())).data(dto).msg(CodeEnum.GOLD_HISTORY_INFO.getMessage()).build();
        }
        return ResultBean.builder().code(200).data(dto).msg("OK").build();
    }


    /**
    * @Author: hongbin
    * @Description: 客户协议pdf ,未实现
    * @DateTime: 11:35 2021/4/23
    * @Params: []
    * @Return java.util.ArrayList<java.util.Map<java.lang.String,java.lang.Object>>
    */
    private ArrayList<Map<String, Object>> getProtocol() {
        ArrayList<Map<String, Object>> lookProtocol = new ArrayList<>();
        HashMap<String, Object> map8 = new HashMap<>();
        map8.put("protocolName", "客户协议");
        map8.put("url", "http://xxx.com");
        lookProtocol.add(map8);
        HashMap<String, Object> map9 = new HashMap<>();
        map9.put("protocolName", "客户协议");
        map9.put("url", "http://xxx.com");
        lookProtocol.add(map9);
        return lookProtocol;
    }

    /**
    * @Author: hongbin
    * @Description: 产品信息
    * @DateTime: 11:35 2021/4/23
    * @Params: [pro]
    * @Return java.util.HashMap<java.lang.String,java.lang.Object>
    */
    private HashMap<String, Object> getProductInfo(GoldAccumulateInfo pro) {
        HashMap<String, Object> basicInformation = new HashMap<>();
        basicInformation.put("productName", pro.getProductName());
        basicInformation.put("issuer", pro.getIssuer());
        basicInformation.put("goldPrice", pro.getGoldPrice());
        basicInformation.put("riskGrade", pro.getRiskGrade());
        return basicInformation;
    }
    /**
    * @Author: hongbin
    * @Description: 支持的银行卡
    * @DateTime: 11:35 2021/4/23
    * @Params: [bankInfos]
    * @Return java.util.List
    */
    private List getSupportBank(List<BankInfo> bankInfos) {
        List supportBankList = new ArrayList<>();

        for (BankInfo bankInfo : bankInfos) {
            HashMap<String, Object> map7 = new HashMap<String, Object>();
            map7.put("image", bankInfo.getIcon());
            map7.put("name", bankInfo.getBankName());
            //每次限额
            map7.put("quotaTime",bankInfo.getQuotaTime());
            //每日限额
            map7.put("quotaDay", bankInfo.getQuotaDay());
            supportBankList.add(map7);
        }
        return supportBankList;
    }
    /**
    * @Author: hongbin
    * @Description: 获取总的收益
    * @DateTime: 11:36 2021/4/23
    * @Params: [interestBearingRules, interestRule, costRule, costRule2]
    * @Return java.util.HashMap<java.lang.String,java.lang.Object>
    */
    private HashMap<String, Object> getEarningsCost(String interestBearingRules, String interestRule, String costRule, String[] costRule2) {
        HashMap<String, Object> earningsCost = new HashMap<>();
        earningsCost.put(interestBearingRules, interestRule);
        earningsCost.put(costRule, costRule2);
        return earningsCost;
    }

    /**
    * @Author: hongbin
    * @Description: PurchaseReceive
    * @DateTime: 11:36 2021/4/23
    * @Params: [pro]
    * @Return java.util.HashMap<java.lang.String,java.lang.Object>
    */
    private HashMap<String, Object> getPurchaseReceive(GoldAccumulateInfo pro) {
        HashMap<String, Object> map6 = new HashMap<>();
        map6.put("minMonetary", pro.getMinMonetary());
        map6.put("ageRange", pro.getAgeRange());
        map6.put("receivePrice", pro.getReceivePrice());
        map6.put("receiveDate", pro.getReceiveDate());
        map6.put("trade_date", pro.getTradeDate());
        map6.put("exchange", pro.getExchange());
        return map6;
    }
    /**
    * @Author: hongbin
    * @Description: SaftyGuarantee,前端写死的数据
    * @DateTime: 11:36 2021/4/23
    * @Params: []
    * @Return java.util.ArrayList<java.lang.Object>
    */
    private ArrayList<Object> getSaftyGuarantee() {
        ArrayList<Object> list = new ArrayList<>();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("image", "http://xxx.png");
        map1.put("text", "知名金融机构");
        list.add(map1);
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("image", "http://xxx.png");
        map2.put("text", "精选优质产品");
        list.add(map2);
        HashMap<String, Object> map3 = new HashMap<>();
        map3.put("image", "http://xxx.png");
        map3.put("text", "监管机构备案");
        list.add(map3);
        return list;
    }
    /**
    * @Author: hongbin
    * @Description: 顶部数据信息
    * @DateTime: 15:14 2021/4/19
    * @Params: [pro, priceInfo]
    * @Return java.util.HashMap<java.lang.String,java.lang.Double>
    */
    private HashMap<String, Double> getTopParam(GoldAccumulateInfo pro, GoldPriceInfo priceInfo) {
        HashMap<String, Double> map = new HashMap<>();
        map.put("referencePrice", priceInfo.getPrice());
        //起购金额
        map.put("theMinimumAmount",pro.getMinMonetary());
        map.put("changePercent", priceInfo.getChangePercent());
        return map;
    }

    /**
    * @Author: hongbin
    * @Description: 支持的银行
    * @DateTime: 11:42 2021/4/23
    * @Params: [bankInfo]
    * @Return int
    */
    @Override
    public int addSupportBank(BankInfo bankInfo) {

        return goldAccumulateDao.addSupportBank(bankInfo);
    }

    /**
     * @Author: hongbin
     * @Description: 查询数据源名称
     * @DateTime: 9:27 2021/4/16
     * @Params: []
     * @Return java.lang.String
     */
    @Override
    public String selectDataTypeName() {
        String dataTypeName = null;
        try {
            Integer goldTpyeId = goldAccumulateDao.getGoldTpye();
            dataTypeName = goldAccumulateDao.selectDataTypeName(goldTpyeId);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONObject.toJSONString(ResultBean.builder().code(808).msg("数据不够").build());
        }

        return JSONObject.toJSONString(ResultBean.builder().code(200).data(dataTypeName).msg("OK").build());
    }
}
